﻿using System;

namespace TimeCalendar
{
    public class MayaDate
    {
        public byte Baktun { get; private set; }
        public byte Katun { get; private set; }
        public byte Tun { get; private set; }
        public byte Uinal { get; private set; }
        public byte Kin { get; private set; }

        public MayaDate(byte baktun, byte katun, byte tun, byte uinal, byte kin)
        {
            if (kin < 0 || kin > 19) throw new Exception("Kin is wrong");
            if (uinal < 0 || kin > 17) throw new Exception("Uinal is wrong");
            if (tun < 0 || tun > 19) throw new Exception("Tun is wrong");
            if (katun < 0 || katun > 19) throw new Exception("Katun is wrong");
            if (baktun < 0 || baktun > 13) throw new Exception("Uinal is wrong");
            Baktun = baktun;
            Katun = katun;
            Tun = tun;
            Uinal = uinal;
            Kin = kin;
        }

        public static Haab GetHaab(MayaDate md)
        {
            var mayaDays = md.Baktun * 144000 + md.Katun * 7200 + md.Tun * 360 + md.Uinal * 20 + md.Kin;
            int myhaab, mykin;
            var x = mayaDays + 348;
            Math.DivRem(x, 365, out myhaab);
            var myuinal = (byte)Math.DivRem(myhaab, 20, out mykin);
            return new Haab(mykin, (UinalNames) myuinal);
        }

        public static Tzolkin GetTzolkin(MayaDate md)
        {
            var mayaDays = md.Baktun * 144000 + md.Katun * 7200 + md.Tun * 360 + md.Uinal * 20 + md.Kin;
            int i13Var, i20Var;
            var x = mayaDays + 159;
            Math.DivRem(x, 13, out i13Var);
            Math.DivRem(x, 20, out i20Var);
            i13Var++;
            return new Tzolkin(i13Var, (KinNames)(byte)i20Var);
        }
    }
}
